<?php
/*
 * @银行账号格式化
 */

function num_format($num) {
        if (!is_numeric($num)) {
                return $num;
        }
        //将数字字符串按4位4位拆分成数组
        $arr = str_split($num, 4);
        $str = implode(' ', $arr);
        return $str;
}
/**
 * 时间格式化
 * @param integer  $timestamp 时间戳
 * @param string $format 格式
 * @return string
 */
function mdate($timestamp = "time()", $format = "Y-m-d H:i") {
	return date($format, $timestamp);
}
/**
 * html 广告代码调用
 *
 * @create time 2013-3-13
 * @author fishinsky
 */
//生成时间编号
function get_time_number() {
	return date("YmdHis") . rand(11, 99);
}

//生成订单号
function get_order_id() {
	$year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
	$order_sn = $year_code[intval(date('Y')) - 2013] .
		strtoupper(dechex(date('m'))) . date('d') .
		substr(time(), -5) . substr(microtime(), 2, 5);
	return $order_sn;
}
function htmlCodeShow($ad_id) {
        //为空则非法

        if (empty($ad_id)) {
                return;
        }
        //注意这里 与infoweb调用的不同数据表
        $adModel = M('ad_ad');
        $ret = $adModel->where("id = '" . $ad_id . "'")->find();
        if ($ret['state'] == 0) {
                return;
        }

        //过期广告不显示
        /*  if (time() >= mkDate($ret['enddatetime']) && mkDate($ret['enddatetime']) != '943891200') {
          return;
          } */
        $id = $ad_id;
        $sort = $ret["sort"];
        $content = $ret["content"];
        $adurl = $ret["adurl"];
        $ad_w = $ret["ad_w"];
        $ad_h = $ret["ad_h"];
        $filename = $ret["filename"];
        //$etime = $ret["enddatetime"];
        $state = $ret["state"];
        $ad_content = '';
        if ((int) $sort == 0) {  //文字广告
                $ad_content = "<a href=" . $adurl . " target=_blank><img src=" . "/Public/defualt/images/kong.gif width=" . $ad_w . " height=" . $ad_h . " border=0>" . $content . "</a>\n";
        } else if ((int) $sort == 1) {  //代码广告
                $ad_content .="" . $content . "\n";
        } else if ((int) $sort == 2) {  //图片广告
                $ad_content = "<a href='" . $adurl . "' target='_blank'>";
                $ad_content .="<img src='" . "" . $filename . "' width='" . $ad_w . "' height='" . $ad_h . "' alt='" . $content . "' title='" . $content . "' />";
                $ad_content .="</a>";
        } else if ((int) $sort == 3) {  //FLASH广告
                $ad_content = "<div id=avs style=width:" . $ad_w . "px;height:" . $ad_h . "px;float=left>\n";
                $ad_content .="<div id=avs_1 style=position:absolute;z-index:0>\n";
                $ad_content .="<a href=" . $adurl . " target=_blank><img src=" . "/Public/defualt/images/kong.gif width=" . $ad_w . " height=" . $ad_h . " border=0></a></div>\n";
                $ad_content .="<object classid=clsid:D27CDB6E-AE6D-11CF-96B8-444553540000 id=obj1 codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0 border=0 width=" . $ad_w . " height=" . $ad_h . ">\n";
                $ad_content .="	<param name=movie value=" . $UploadFolder . $filename . ">\n";
                $ad_content .= "	<param name=quality value=High>\n";
                $ad_content .= " <param name=wmode value=transparent>\n";
                $ad_content .= "	<embed src=" . $filename . " pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash name=obj1 width=" . $ad_w . " height=" . $ad_h . "></object>\n";
                $ad_content .= "<br/>\n";
                $ad_content .= "</div>)";
        }
        return $ad_content;
}

/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code) {
        static $_status = array(
            // Informational 1xx
            100 => 'Continue',
            101 => 'Switching Protocols',
            // Success 2xx
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            // Redirection 3xx
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Moved Temporarily ', // 1.1
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            // 306 is deprecated but reserved
            307 => 'Temporary Redirect',
            // Client Error 4xx
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            // Server Error 5xx
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            509 => 'Bandwidth Limit Exceeded'
        );
        if (isset($_status[$code])) {
                header('HTTP/1.1 ' . $code . ' ' . $_status[$code]);
                // 确保FastCGI模式下正常
                header('Status:' . $code . ' ' . $_status[$code]);
        }
}
function is_gb2312($str) {
	for ($i = 0; $i < strlen($str); $i++) {
		$v = ord($str[$i]);
		if ($v > 127) {
			if (($v >= 228) && ($v <= 233)) {
				if (($i + 2) >= (strlen($str) - 1))
					return true;  // not enough characters  
				$v1 = ord($str[$i + 1]);
				$v2 = ord($str[$i + 2]);
				if (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191)) // utf编码  
					return false;
				else
					return true;
			}
		}
	}
	return true;
}
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
	return $relate_url;
}

//加密2
function pwSha($password) {
	return md5(C('AUTH_KEY') . sha1(C('AUTH_KEY') . $password));
}
/**
 * @param string $string 原文或者密文
 * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
 * @param string $key 密钥
 * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
 *
 * @example
 *
 *  $a = authcode('abc', 'ENCODE', 'key');
 *  $b = authcode($a, 'DECODE', 'key');  // $b(abc)
 *
 *  $a = authcode('abc', 'ENCODE', 'key', 3600);
 *  $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
 */
function authcode($string, $operation = 'DECODE', $expiry = 0, $key = '') {
	$ckey_length = 4;
// 随机密钥长度 取值 0-32;
// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
// 当此值为 0 时，则不产生随机密钥
	$key = md5($key ? $key : C('AUTH_KEY'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya . md5($keya . $keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr(strtr($string, '-_', '+/'), $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for ($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for ($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for ($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if ($operation == 'DECODE') {
		if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc . strtr(str_replace('=', '', base64_encode($result)), '+/', '-_');
	}
}
//发送邮件
function send_mail($address, $name, $subject, $body) {
	$mail = new \org\PHPMailer;
	$mail->IsSMTP();
	$mail->SMTPAuth = true;    // enable SMTP authentication
	$mail->Host = C("email.host"); // sets the SMTP server
	$mail->Port = C("email.port");
	$mail->Username = C("email.email"); // SMTP account username
	$mail->Password = C("email.password"); // SMTP account password
	$mail->CharSet = "utf-8";   // 这里指定字符集！
	$mail->Encoding = "base64";
	$mail->SetFrom(C("email.email"), C("email.from"));

	$mail->Subject = $subject;

	$mail->MsgHTML($body);

	$mail->AddAddress($address, $name);
	if (!$mail->Send()) {
		return "Mailer Error: " . $mail->ErrorInfo;
	} else {
		return true;
	}
}
